#include<iostream>
#include<string>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<cstdio>
#include<cassert>
#include<cstdlib>
#include<cstring>



#define NUM 2
#define SIZE 1024

void Reader(int fd)
{
    char buffer[SIZE];
    while (true)
    {
        //sleep(100);
        buffer[0] = 0;

        ssize_t n = read(fd,buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = '\0';
            std::cout << "father say:["<<"PID : "<< getpid() <<"]: " << buffer<<std::endl;
        }
        break;
        if(n == 0)
        {
            std:: cout << "read 0"<<std::endl;    
        }
        
        
        //sleep(1);
    }
    
}
void Writer(int fd)
{
    char buffer[SIZE];
    std::string msg = "hello I am child";
    int num = 1;

    while (true)
    {
        buffer[0] = 0;
        snprintf(buffer,sizeof(buffer),"child-PID: ""%d-%s-%d",getpid(),msg.c_str(),num);
        num++;
        //写入管道
        write(fd,buffer,strlen(buffer));
        sleep(1);
        //break;
    }

}


int main()
{
    int pipefd[NUM] = {0};
    
    //创建管道
    int n = pipe(pipefd);
    if(n < 0 ) return -1;
    
    //创建子进程
    pid_t id = fork();
    if( id < 0) return -2;
    if(id == 0)
    {
        close(pipefd[0]);//关闭读端
        //todo
        
        Writer(pipefd[1]);

        //close(pipefd[1]);
        std::cout << "child exit"<<std::endl;
        exit(0);
    }

    //FatherPrc
    close(pipefd[1]);
    

    //读取任务
    Reader(pipefd[0]);
    close(pipefd[0]); 
    std::cout<<"reader_exit"<<std::endl;

    int status;
    pid_t ret = waitpid(id,&status,0);
    if(ret > 0)
    {
        std::cout << "success return " << "exit_code: "<<WEXITSTATUS(status)
            <<" exit_signal: "<<WTERMSIG(status)<<std::endl;
    }

    return 0;
}